package com.dp.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.dp.common.utils.DateUtils;
import com.dp.common.utils.StringUtils;
import com.dp.system.domain.SysAlarmLog;
import com.dp.system.domain.SysAlarmRule;
import com.dp.system.domain.SysTemperature;
import com.dp.system.mapper.SysTemperatureMapper;
import com.dp.system.service.ISysAlarmLogService;
import com.dp.system.service.ISysAlarmRuleService;
import com.dp.system.service.ISysTemperatureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 温度记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-10
 */
@Service
public class SysTemperatureServiceImpl implements ISysTemperatureService {

    @Autowired
    private SysTemperatureMapper sysTemperatureMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate; // 用于执行原生 SQL 重置自增

    @Autowired
    private ISysAlarmRuleService sysAlarmRuleService; // 注入报警规则服务

    @Autowired
    private ISysAlarmLogService sysAlarmLogService; // 注入报警记录服务

    /**
     * 查询温度记录
     *
     * @param temperatureId 温度记录主键
     * @return 温度记录
     */
    @Override
    public SysTemperature selectSysTemperatureByTemperatureId(Long temperatureId) {
        return sysTemperatureMapper.selectSysTemperatureByTemperatureId(temperatureId);
    }

    /**
     * 查询温度记录列表
     *
     * @param sysTemperature 温度记录
     * @return 温度记录列表
     */
    @Override
    public List<SysTemperature> selectSysTemperatureList(SysTemperature sysTemperature) {
        return sysTemperatureMapper.selectSysTemperatureList(sysTemperature);
    }

    /**
     * 新增温度记录
     *
     * @param sysTemperature 温度记录
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSysTemperature(SysTemperature sysTemperature) {
        // 1. 保存温度记录
        sysTemperature.setCreateTime(DateUtils.getNowDate());
        sysTemperature.setUpdateTime(DateUtils.getNowDate()); // 设置更新时间
        int rows = sysTemperatureMapper.insertSysTemperature(sysTemperature);

        // 2. 检查并生成报警记录
        generateAlarmLog(sysTemperature);

        return rows;
    }

    /**
     * 生成报警记录逻辑
     * @param temperature 新插入的温度记录
     */
    private void generateAlarmLog(SysTemperature temperature) {
        Long greenhouseId = temperature.getGreenhouseId();
        BigDecimal temperatureValue = temperature.getTemperatureValue();
        Long temperatureId = temperature.getTemperatureId();

        // 获取该大棚的报警规则
        SysAlarmRule alarmRule = sysAlarmRuleService.selectSysAlarmRuleByGreenhouseId(greenhouseId);

        if (alarmRule != null) {
            BigDecimal minTemp = alarmRule.getMinTemperature();
            BigDecimal maxTemp = alarmRule.getMaxTemperature();
            Long ruleId = alarmRule.getRuleId();

            // 检查温度是否超限
            if (temperatureValue.compareTo(minTemp) < 0 || temperatureValue.compareTo(maxTemp) > 0) {
                SysAlarmLog alarmLog = new SysAlarmLog();
                alarmLog.setRuleId(ruleId);
                alarmLog.setGreenhouseId(greenhouseId);
                alarmLog.setTemperatureId(temperatureId);
                alarmLog.setAlarmTime(DateUtils.getNowDate());
                alarmLog.setAlarmMessage(buildAlarmMessage(temperatureValue, minTemp, maxTemp));

                // 插入报警记录
                sysAlarmLogService.insertSysAlarmLog(alarmLog);
            }
        }
    }

    /**
     * 构建报警消息
     */
    private String buildAlarmMessage(BigDecimal temp, BigDecimal min, BigDecimal max) {
        if (temp.compareTo(min) < 0) {
            return "低温报警：当前温度" + temp + "低于最低阈值" + min;
        } else {
            return "高温报警：当前温度" + temp + "高于最高阈值" + max;
        }
    }

    /**
     * 修改温度记录
     *
     * @param sysTemperature 温度记录
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSysTemperature(SysTemperature sysTemperature) {
        // 1. 获取原始数据
        SysTemperature original = selectSysTemperatureByTemperatureId(sysTemperature.getTemperatureId());

        // 2. 执行更新操作
        sysTemperature.setUpdateTime(DateUtils.getNowDate());
        int rows = sysTemperatureMapper.updateSysTemperature(sysTemperature);

        if (rows > 0 && sysTemperature.getTemperatureValue() != null) {
            // 3. 检查温度变化
            if (original != null && !sysTemperature.getTemperatureValue().equals(original.getTemperatureValue())) {
                // 4. 获取更新后的完整数据
                SysTemperature updated = selectSysTemperatureByTemperatureId(sysTemperature.getTemperatureId());
                checkAndGenerateAlarm(updated);
            }
        }
        return rows;
    }

    // 新增报警检查方法
    private void checkAndGenerateAlarm(SysTemperature temperature) {
        Long greenhouseId = temperature.getGreenhouseId();
        BigDecimal currentTemp = temperature.getTemperatureValue();

        // 获取报警规则
        SysAlarmRule rule = sysAlarmRuleService.selectSysAlarmRuleByGreenhouseId(greenhouseId);
        if (rule == null) return;

        // 阈值检查
        boolean isOverLimit = currentTemp.compareTo(rule.getMaxTemperature()) > 0
                || currentTemp.compareTo(rule.getMinTemperature()) < 0;

        if (isOverLimit) {
            generateAlarmLog(temperature, rule);
        }
    }

    // 重构报警生成方法
    private void generateAlarmLog(SysTemperature temp, SysAlarmRule rule) {
        SysAlarmLog alarmLog = new SysAlarmLog();
        alarmLog.setRuleId(rule.getRuleId());
        alarmLog.setGreenhouseId(temp.getGreenhouseId());
        alarmLog.setTemperatureId(temp.getTemperatureId());
        alarmLog.setAlarmTime(DateUtils.getNowDate());
        alarmLog.setAlarmMessage(buildAlarmMessage(
                temp.getTemperatureValue(),
                rule.getMinTemperature(),
                rule.getMaxTemperature()
        ));
        sysAlarmLogService.insertSysAlarmLog(alarmLog);
    }

    /**
     * 批量新增温度记录（核心改造方法）
     */
    @Override
    @Transactional
    public void batchInsertSysTemperature(List<SysTemperature> temperatureList) {
        if (CollectionUtils.isEmpty(temperatureList)) {
            return;
        }

        // 统一设置创建时间和更新时间（避免每条数据单独设置）
        Date now = DateUtils.getNowDate();
        for (SysTemperature temp : temperatureList) {
            temp.setCreateTime(now);
            temp.setUpdateTime(now);
            // 确保greenhouseId已正确设置（根据实际业务可能需要从上下文获取）
            if (temp.getGreenhouseId() == null) {
                throw new IllegalArgumentException("greenhouseId cannot be null");
            }
        }

        sysTemperatureMapper.batchSysTemperature(temperatureList);

        // 对每条数据单独检查报警
        for (SysTemperature temp : temperatureList) {
            generateAlarmLog(temp);
        }
    }

    /**
     * 批量删除温度记录
     *
     * @param temperatureIds 需要删除的温度记录主键数组
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSysTemperatureByTemperatureIds(Long[] temperatureIds) {
        int deleteCount = sysTemperatureMapper.deleteSysTemperatureByTemperatureIds(temperatureIds);
        if (deleteCount > 0) {
            resetAutoIncrementAfterDelete(); // 删除后重置自增 ID
        }
        return deleteCount;
    }

    /**
     * 删除温度记录信息（单条）
     *
     * @param temperatureId 温度记录主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSysTemperatureByTemperatureId(Long temperatureId) {
        int deleteCount = sysTemperatureMapper.deleteSysTemperatureByTemperatureId(temperatureId);
        if (deleteCount > 0) {
            resetAutoIncrementAfterDelete(); // 删除后重置自增 ID
        }
        return deleteCount;
    }

    /**
     * 获取温度历史数据
     *
     * @return 温度历史数据列表
     */
    @Override
    public List<SysTemperature> getTemperatureHistoryData() {
        return sysTemperatureMapper.getTemperatureHistoryData();
    }

    /**
     * 获取实时温度数据
     *
     * @return 实时温度数据列表
     */
    @Override
    public List<SysTemperature> getRealTimeTemperatureData() {
        return sysTemperatureMapper.selectRealTimeTemperatureData();
    }


    /**
     * 获取带大棚名称的实时温度数据
     *
     * @return 带名称的实时温度数据列表
     */
    @Override
    public List<SysTemperature> selectRealTimeTemperatureDataWithName() {
        return sysTemperatureMapper.selectRealTimeTemperatureDataWithName();
    }

    /**
     * 私有方法：删除后重置 AUTO_INCREMENT
     */
    private void resetAutoIncrementAfterDelete() {
        // 查询当前最大 ID（处理空表情况：MAX 返回 NULL 时设为 0）
        Long maxId = jdbcTemplate.queryForObject(
                "SELECT MAX(temperature_id) FROM sys_temperature",
                Long.class
        );
        long autoIncrementValue = (maxId != null) ? maxId : 0;
        autoIncrementValue = autoIncrementValue + 1; // 自增起始值为当前最大 ID + 1

        // 执行 SQL 重置自增
        jdbcTemplate.execute(
                "ALTER TABLE sys_temperature AUTO_INCREMENT = " + autoIncrementValue
        );
    }
}